package ftest.movie.appLogic2;

import java.util.Random;

import ftest.movie.appLogic.UserHelper;
import ftest.movie.model.User;
import ftest.movie.pages.UserProfilePage;

public class UserHelper2 extends DriverBasedHelper implements UserHelper {

  public UserHelper2(ApplicationManager2 manager) {
    super(manager.getWebDriver());
  }

  @Override
  public void loginAs(User user) {
    pages.loginPage.ensurePageLoaded()
      .setUsernameField(user.getLogin())
      .setPasswordField(user.getPassword())
      .clickSubmitButton();
  }

  @Override
  public void logout() {
    pages.internalPage.ensurePageLoaded()
      .clickLogoutLink();
  }

  @Override
  public boolean isLoggedIn() {
    return pages.internalPage.waitPageLoaded();
  }

  @Override
  public boolean isLoggedInAs(User user) {
    return isLoggedIn()
        && getLoggedUser().getLogin().equals(user.getLogin());
  }

  @Override
  public boolean isNotLoggedIn() {
    return pages.loginPage.waitPageLoaded();
  }
  
  private User getLoggedUser() {
    UserProfilePage userProfile = pages.internalPage.ensurePageLoaded()
      .clickUserProfilePage()
      .ensurePageLoaded();
    return new User()
      .setLogin(userProfile.getUsername())
      .setEmail(userProfile.getEmail())
      .setRole(userProfile.getRole());
  }
  
  @Override
public String generateMovieId(){
	  Random rnId = new Random();
	  int randomNumber = rnId.nextInt(100 - 1) + 1;
	  return "" + randomNumber;
  }

@Override
public void createUser(User user) {
	pages.userManagementPage.open();
	fillNewUserForm(user);
  }

private void fillNewUserForm(User user) {
	input(pages.userManagementPage.usernameField, user.getLogin());
	input(pages.userManagementPage.emailField, user.getEmail());
	input(pages.userManagementPage.passwordField, user.getPassword());
	input(pages.userManagementPage.password2Field, user.getPassword());
	pages.userManagementPage.permissionDropdown().selectByValue(user.getRole());
	pages.userManagementPage.clickSaveUserButton();
}

@Override
public boolean isValidationMessagePresent() {
	return pages.userManagementPage.validationMsg.isDisplayed();
}
}
